<?php
/*
 *  This file is part of Urd.
 *
 *  Urd is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 3 of the License, or
 *  (at your option) any later version.
 *  Urd is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program. See the file "COPYING". If it does not
 *  exist, see <http://www.gnu.org/licenses/>.
 *
 * $LastChangedDate: 2008-07-15 15:42:06 +0200 (Tue, 15 Jul 2008) $
 * $Rev: 1296 $
 * $Author: gavinspearhead $
 * $Id: browse.php 1296 2008-07-15 13:42:06Z gavinspearhead $
 */
if (!defined('ORIGINAL_PAGE')) define('ORIGINAL_PAGE', $_SERVER['PHP_SELF']);

$pathidx = realpath(dirname(__FILE__));

require_once "$pathidx/../functions/html_includes.php";
if (!isset($_SESSION['setdata']) || !is_array($_SESSION['setdata'])) 
    $_SESSION['setdata'] = array();

$rprefs = load_config($db);

$message = '';

$sort_orders = array ('', 'setname', 'timestamp', 'size', 'better_subject', 'rating');
$feed_id = get_request('feed_id', 0);

$show_advanced_search = FALSE;

// get last update times for groups
$sql = "SELECT \"feedid\", \"last_update_seen\" FROM userfeedinfo WHERE \"userid\" = '$userID'";

if ($feed_id != 0)
    $sql .= " AND \"feedid\" = '$feed_id'";
$res = $db->execute_query($sql);
$feed_lastupdate = array();
if ($res !== FALSE) {
    foreach ($res as $row) 
        $feed_lastupdate["{$row['feedid']}"] = $row['last_update_seen'];
}

// Process actions:
if ($_SERVER['REQUEST_METHOD'] == 'POST') 
    $message = process_which_button($db,$userID, USERSETTYPE_RSS, $feed_id, $__message);


// Create title:
$totbin = get_total_rss_sets($db);
$title = $LN['urdname'] . ' - '. $LN['browse_download'] . ' ' . $LN['from'] . ' ' . $totbin. ' ' . $LN['sets'] . '!';  // todo

// Get the required values:
// ori = passed back to the front-end, these are used in the database (backend):
$feed_id = $origfeed_id = get_request('feed_id',0);
$search = html_entity_decode(get_request('search', ''));
if (utf8_decode($search) == html_entity_decode('<' . $LN['search'] . '>'))
    $search = '';
$orisearch  = utf8_decode($search);
$offset  = $orioffset  = get_request('offset', 0);
$maxage  = $orimaxage  = get_request('maxage', 0);
$order   = $oriorder   = get_request('order', '');
$flag    = $oriflag    = get_request('flag', '');

$maxage  = $orimaxage  = get_request('maxage', '');
$minage  = $oriminage  = get_request('minage', '');
$ominsetsize = get_request('minsetsize', NULL);
$omaxsetsize = get_request('maxsetsize', NULL);
$maxrating  = $orimaxrating  = get_request('maxrating', '');
$minrating  = $oriminrating  = get_request('minrating', '');
$setid   = get_request('setid','');

$db->escape($feed_id);
$db->escape($search);
$db->escape($offset);
$db->escape($maxage);
$db->escape($order);
$db->escape($flag);
$db->escape($setid);

$db->escape($maxage);
$db->escape($minage);
$db->escape($minrating);
$db->escape($maxrating);
// Get the newsgroups:
$res = $db->execute_query('SELECT rss_urls."id", "name" FROM rss_urls LEFT JOIN userfeedinfo ON rss_urls."id" = "feedid"' . 
    " WHERE \"subscribed\" = '". RSS_SUBSCRIBED . "' AND (\"visible\" > 0 OR \"visible\" IS NULL OR \"feedid\" = '$feed_id') ORDER BY \"name\"");
if (!$res) 
    $res = array();

$c = 0;
$next = $prev = '';
$subscribedfeeds = array();
foreach ($res as $arr) {
    //list($size, $suffix) = format_size($arr['postcount'],'h', '', 1000);
    $subscribedfeeds[] = array(
        'id'=>$arr['id'], 
        'name'=>$arr['name'], 
    );
    if ($arr['id'] == $feed_id) {
        $next = $c+1;
        $prev = $c-1;
    }
    $c++;
}

if (isset($subscribedfeeds[$next]['id']))
    $next_feed = $subscribedfeeds[$next]['id'];
else 
    $next_feed = '';

if (isset($subscribedfeeds[$prev]['id']))
    $prev_feed = $subscribedfeeds[$prev]['id'];
else 
    $prev_feed = '';

// Build the page skipper:

// Determine maximum sets to be displayed, and display the current page:
$Qfeed = $Qsearch = $Qage = $Qsize = $Qflag = $Qsetid = $Qkill = $Qrating = $Qnewfeed1 = $Qnewfeed2 = '';

$search_type = $db->get_pattern_search_command('LIKE'); // get the operator we need for the DB LIKE for mysql or ~~* for postgres

if ($feed_id != 0 && $feed_id != '') {
    $Qfeed = "AND \"rss_id\" = $feed_id ";
    $Qnewfeed1 = " userfeedinfo.\"feedid\" = rss_sets.\"rss_id\" ";
} else {
    $Qfeed = ' ' ;
    $Qnewfeed1 = "userfeedinfo.\"feedid\" = rss_sets.\"rss_id\" ";
    $Qnewfeed2 = "AND (userfeedinfo.\"visible\" = 1 OR userfeedinfo.\"visible\" IS NULL) ";
}
// Search google style:
if ($search != '') {
    $search = trim(str_replace('*',' ',$search));
    $keywords = explode(' ',$search);
    $Qsearch1 = $Qsearch2 = '';
    foreach ($keywords as $keyword) {
        if ($keyword[0] == '-') {
            $not = 'NOT';
            $keyword = ltrim($keyword, '-');
        } else 
            $not = '';

        if ($keyword != '') {
            $Qsearch1 .= "AND $not rss_sets.\"setname\" $search_type '%{$keyword}%' "; 
            $Qsearch2 .= " $not extsetdata2.\"value\" $search_type '%{$keyword}%' AND ";
        }
    }
    $Qsearch .= $Qsearch1 . ' OR ' . $Qsearch2 . '1=1';
}

if (is_numeric($maxage) && $maxage > 0) {
    $Qage .= 'AND ('. time() . " - timestamp) / 3600 / 24 <= $maxage ";
    $show_advanced_search = TRUE;
} else 
    $maxage = '';
if (is_numeric($minage) && $minage > 0) {
    $show_advanced_search = TRUE;
    $Qage .= 'AND ('. time() . " - timestamp) / 3600 / 24 >= $minage ";
} else 
    $minage = '';

if (isset ($prefs['maxsetsize']))
    $maxsetsize = $prefs['maxsetsize'];
else 
    $maxsetsize = 0;
 

if (isset ($prefs['minsetsize']))
    $minsetsize = $prefs['minsetsize'];
else 
    $minsetsize = 0;

if (is_numeric($ominsetsize))  {
    $show_advanced_search = TRUE;
    $minsetsize = $ominsetsize * 1024 * 1024;
    $db->escape($minsetsize, TRUE);
    $Qsize = " AND ( rss_sets.\"size\" >= $minsetsize ) ";
} else if ($Qsearch == '') {
    $Qsize = " AND ( rss_sets.\"size\" >= ((SELECT CASE WHEN \"minsetsize\" IS NULL THEN $minsetsize ELSE \"minsetsize\" END) * 1024 * 1024))";
}

if (is_numeric($omaxsetsize))  {
    $maxsetsize = $omaxsetsize * 1024 * 1024;
    $show_advanced_search = TRUE;
    $db->escape($maxsetsize, TRUE);
    $Qsize .= " AND ( rss_sets.size <= $maxsetsize ) ";
} else if ($Qsearch == '') {
    if  ($maxsetsize == 0)
        $Qsize .= " AND (userfeedinfo.\"maxsetsize\" = 0 OR \"maxsetsize\" IS NULL OR rss_sets.\"size\" <= ( \"maxsetsize\" * 1024 * 1024)) ";
    else 
        $Qsize .= " AND (userfeedinfo.\"maxsetsize\" = 0 OR (rss_sets.\"size\" <= ((SELECT CASE WHEN \"maxsetsize\" IS NULL THEN $maxsetsize ELSE \"maxsetsize\" END) * 1024 * 1024 ))) ";
}


if($setid != '')
    $Qsetid = " AND \"id\"='$setid' ";

if (is_numeric ($minrating)) {
    $show_advanced_search = TRUE;
    $Qrating .= " AND (CAST(extsetdata3.\"value\" AS DECIMAL(5,2)) >= $minrating) "; 
}
if (is_numeric ($maxrating)) {
    $show_advanced_search = TRUE;
    $Qrating .= " AND (CAST(extsetdata3.\"value\" AS DECIMAL(5,2)) <= $maxrating) ";
}

$rss_flag = '';

$killflag = FALSE;
if ($flag == 'read') {
    $Qflag = ' AND usersetinfo."statusread"=1 ';
    $Qkill = ' AND (usersetinfo."statuskill" != 1 OR usersetinfo."statuskill" IS NULL)';
} else if ($flag == 'kill') {
    $killflag = TRUE;
    $Qkill = ' AND usersetinfo."statuskill"=1 ';
} else if ($flag == 'interesting') {
    $Qkill = ' AND (usersetinfo."statuskill" != 1 OR usersetinfo."statuskill" IS NULL)';
    $Qflag = ' AND usersetinfo."statusint"=1 ';
    $rss_flag = "&amp;flag=interesting&amp;userid=$userID";
} else if ($flag == 'nzb') {
    $Qflag = ' AND usersetinfo."statusnzb"=1 ';
    $Qkill = ' AND (usersetinfo."statuskill" != 1 OR usersetinfo."statuskill" IS NULL)';
} else 
    $Qkill = ' AND (usersetinfo."statuskill" != 1 OR usersetinfo."statuskill" IS NULL)';

// Validation of order:
list($def_sort, $def_sort_order) = explode (' ', (isset($prefs['defaultsort']) ? ($prefs['defaultsort'] . ' ') : 'setname asc'), 2);

if (strtolower($def_sort) == 'subject') $def_sort = 'setname';
if (strtolower($def_sort) == 'date') $def_sort = 'timestamp';

$def_sort .= ' ' . $def_sort_order;

$orderfield = '';
if ($order != '')
    list($order, $orderfield) = explode(' ', $order . ' ', 2); // add space in case it is a single word

if ($order == 'setname') 
    $order = 'better_subject';

$perpage = get_maxperpage($db, $userID);

// make the rss URL
$rss_limit = $perpage;


if (isset ($prefs['minsetsize']))
    $minsetsize = $prefs['minsetsize'];
else 
    $minsetsize = 0;

if ($feed_id == 0) {
    $rss_feedid = '0';
    $rss_minsetsize = $minsetsize;
} else {
    $rss_minsetsize = get_minsetsize_feed($db, $feed_id, $userID, $minsetsize);
    $rss_feedid = $feed_id;
}
$rss_maxage = $maxage;
$url = $rprefs['url']; 

$rssurl = $url . "html/rss.php?feed_id=$rss_feedid&amp;limit=$rss_limit&amp;minsize=$rss_minsetsize&amp;maxage=$rss_maxage$rss_flag";

if (!in_array(strtolower($order), $sort_orders))
    $Qorder = $def_sort;
else if (!empty($order)) {
    if ($order == 'rating') 
        $order = 'extsetdata3.value IS NULL, CAST(extsetdata3."value" AS decimal(5,2))';
    $Qorder = $order . " $orderfield";
} else 
    $Qorder = $def_sort;

if($setid != '') {
    // when searching for a set ID (from RSS) we remove all other limits
    $Qfeed = $Qsearch = $Qage = $Qsize = $Qflag = '';
    $Qsetid = " AND rss_sets.\"setid\" $search_type '$setid' ";
}

// Get maximum:
$basic_query =  
    " FROM rss_sets " . 
    " LEFT JOIN userfeedinfo ON ($Qnewfeed1 AND userfeedinfo.\"userid\" = $userID) " .
    " LEFT JOIN usersetinfo ON (usersetinfo.\"setID\" = rss_sets.\"setid\") AND (usersetinfo.\"userID\" = $userID ) AND (usersetinfo.\"type\" = '" . USERSETTYPE_RSS . "')" . 
    " LEFT JOIN extsetdata AS extsetdata2 ON (extsetdata2.\"setID\" = rss_sets.\"setid\") AND extsetdata2.\"name\" = 'setname' AND extsetdata2.\"type\" = '" . USERSETTYPE_RSS . "' " .
    " LEFT JOIN extsetdata AS extsetdata1 ON (extsetdata1.\"setID\" = rss_sets.\"setid\") AND extsetdata1.\"name\" = 'link' AND extsetdata1.\"type\" = '" . USERSETTYPE_RSS . "' " .
    " LEFT JOIN extsetdata AS extsetdata3 ON (extsetdata3.\"setID\" = rss_sets.\"setid\") AND extsetdata3.\"name\" = 'score' AND extsetdata3.\"type\" = '" . USERSETTYPE_RSS . "' " .
    " WHERE (1=1 $Qnewfeed2 $Qfeed $Qsearch $Qflag $Qsetid $Qsize $Qkill $Qrating) AND (1=1 $Qage OR usersetinfo.\"statusint\" = 1) ";
$sql = 'SELECT COUNT(rss_sets."id") AS cnt ' . $basic_query;
$res = $db->execute_query($sql);
if ($res === FALSE || !isset($res[0]['cnt'])) 
    throw new exception($LN['error_setsnumberunknown']);
$totalsets = $res[0]['cnt'];

if ($orioffset >= $totalsets){
    $orioffset = $offset = 0;
    $db->escape($offset);

// Build pages array:
$size = SKIPPER_SIZE;
$totalpages = ceil($totalsets / $perpage);      // Total number of pages.
$activepage = ceil(($offset+1) / $perpage);     // This is the page we're on. (+1 because 0/100 = page 1)
$start = max($activepage - floor($size/2), 1);  // We start at 1 unless we're now on page 12, then we show page 2.
$end = min($start + $size, $totalpages);        // We don't go beyond 'totalpages' ofcourse.
$start = max($end - $size, 1);                  // Re-check $start, in case the pagenumber is near the end
$pages = array();
$params = "&feed_id={$feed_id}&maxage={$maxage}&search={$search}&order={$order}&flag={$flag}&minsetsize={$ominsetsize}&maxsetsize={$omaxsetsize}&minrating={$oriminrating}&maxrating={$orimaxrating}";
for ($i = 1; $i <= $totalpages; $i++) {
    $thispage = array();
    $thispage['number'] = $i;
    $pageoffset = ($i - 1) * $perpage;          // For page 1, offset = 0.
    $url = $_SERVER['PHP_SELF'] . "?offset={$pageoffset}" . $params;
    $url = htmlspecialchars($url);
    $thispage['url'] = $url;
    // distance is the distance from the current page, maximum of 5. Used to colour close pagenumbers:
    $thispage['distance'] = min(abs($activepage - $i),5);
    $pages[] = $thispage;
}

$now = time();
$sql = " *, ($now - \"timestamp\") AS \"age\", \"timestamp\", usersetinfo.\"statusint\" AS interesting, " .
    " usersetinfo.\"statusnzb\" AS \"nzbcreated\", usersetinfo.\"statusread\" AS \"alreadyread\", extsetdata2.\"value\" AS \"bettername\", extsetdata1.\"value\" AS imdblink, " .
        " (CASE WHEN extsetdata3.\"value\" IS NULL THEN '0' ELSE extsetdata3.\"value\" END) AS rating, " .
    " (CASE WHEN extsetdata2.\"value\" IS NULL THEN rss_sets.\"setname\" ELSE extsetdata2.\"value\" END) AS better_subject " .
    $basic_query . 
    " ORDER BY (usersetinfo.\"statusint\" <> 1 OR usersetinfo.\"statusint\" IS NULL) ASC, $Qorder";

//echo $sql;
$setres = $db->select_query($sql, $perpage, $offset); 

// Get the set data
$allsets = array();
// If no sets exist, create empty array:
if (!is_array($setres)) 
    $setres = array();
$number = $offset;

foreach ($setres as $arr) {
    // Show bar around interesting when applicable:
    $thisset = array();
    $thisset['interesting'] = $arr['statusint'];
    $thisset['sid'] = $arr['setid'];
    $thisset['added'] = (is_array($_SESSION['setdata']) && in_setdata($arr['id'], 'rss', $_SESSION['setdata'])) ? 1 : 0; // todo
    $thisset['nzb'] = $arr['nzbcreated'];
    $thisset['read'] = $arr['alreadyread'];
    $thisset['setname'] = $arr['setname']; 
    $thisset['link'] = $arr['nzb_link'];
    if ($arr['imdblink'] != NULL)
        $thisset['imdblink'] = $arr['imdblink'] ;
    else 
        $thisset['imdblink'] = '';
    if ($arr['rating'] != 0)
        $thisset['rating'] = sprintf("%.1f", $arr['rating']);
    else 
        $thisset['rating'] = '';

    if ($arr['bettername'] != '') 
        $thisset['setname'] = $arr['bettername'];
    else {
        $clearname = $arr['setname'];
        // filter common spam in subjects
        $name = preg_replace('/(\byEnc\b)|(\breq:)|(\bwww\.[\w\.]*\b)|(\bhttp:\/\/[\w\.]*\b)|([=><#])/i', '', $clearname);
        $thisset['setname'] = utf8_decode($name);// we utf8_encode before putting it in the db (otherwise pg will complain); but why need we decode it here so that all funny (german) characters are shown properly???
    }

    $complete = 100;
    $thisset['complete'] = $complete;
    $feed_id = $arr['rss_id'];
    if (isset($_SESSION['last_login']) && isset ($feed_lastupdate["$feed_id"]) && $_SESSION['last_login'] > 0 && $feed_lastupdate["$feed_id"] > 0) {
        $last_check_time = min($_SESSION['last_login'], $feed_lastupdate["$feed_id"]);
        $thisset['new_set'] = ($arr['date'] > $last_check_time) ? 1 : 0;
    } else
        $thisset['new_set'] = 0;
    $now = time();
    $age = ($now > $arr['timestamp']) ? $now - $arr['timestamp'] : 0;

    $thisset['age'] = readable_time($age,'largest_two');
    $thisset['size'] = readable_size($arr['size'], 1, $LN['byte_short']);
    $number++;
    $thisset['number'] = $number;
    $allsets[] = $thisset;
}


init_smarty($title);
$smarty->assign('rssurl',       $rssurl);

$smarty->assign('search',       $orisearch);
$smarty->assign('feed_id',      $origfeed_id);
$smarty->assign('offset',       $orioffset);
$smarty->assign('maxage',       $orimaxage);
$smarty->assign('order',        $oriorder);
$smarty->assign('flag',         $oriflag);
$smarty->assign('maxage',       $orimaxage);
$smarty->assign('minage',       $oriminage);
$smarty->assign('maxrating',    $orimaxrating);
$smarty->assign('minrating',    $oriminrating);
$smarty->assign('next_feed',	$next_feed);
$smarty->assign('prev_feed',	$prev_feed);
$smarty->assign('isadmin',		$isadmin);

$smarty->assign('minsetsize',   $ominsetsize);
$smarty->assign('maxsetsize',   $omaxsetsize);
$smarty->assign('show_advanced_search', (int) $show_advanced_search);
$smarty->assign('killflag',     $killflag);
$smarty->assign('subscribedfeeds',  $subscribedfeeds);
$smarty->assign('pages',        $pages);
$smarty->assign('lastpage',     $totalpages);
$smarty->assign('currentpage',      $activepage);
$smarty->assign('allsets',      $allsets);
$smarty->assign('countsets',        count($allsets));
$smarty->assign('__message',        $__message);
$smarty->assign('maxstrlen',        $prefs['maxsetname']);
$smarty->assign('message',      $message);
$smarty->assign('seteditor',        is_seteditor($db, $userID));
$smarty->assign('USERSETTYPE_GROUP',    USERSETTYPE_GROUP);
$smarty->assign('USERSETTYPE_RSS',      USERSETTYPE_RSS);

$smarty->display('rsssets.tpl');

?>
